package com.cheer.security;

import com.cheer.enums.ResultEnum;
import com.cheer.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author cheer
 */
@Component
public class RestAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        Result<Void> result = Result.error(ResultEnum.SERVER_ERROR);

        if (exception instanceof BadCredentialsException || exception instanceof UsernameNotFoundException) {
            result = Result.error(ResultEnum.ACCOUNT_ERROR, "账号或密码不正确");
            request.getSession().setAttribute(SecurityConfig.FAILED_LOGIN, true);

        } else if (exception instanceof DisabledException) {
            result = Result.error(ResultEnum.SERVER_ERROR, "账号注册未通过，无法再登录系统");

        } else if (exception instanceof ValidateCodeException) {
            result = Result.error(ResultEnum.SERVER_ERROR, exception.getMessage());
        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(objectMapper.writeValueAsString(result));
        response.getWriter().flush();
    }

}
